package com.ccsu.mymarket.testUploadFile.Storage;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
@Slf4j
public class FileSystemStorageService implements StorageService {

	private final Path rootLocation;

	public FileSystemStorageService(@Value("${storage.location}")Path rootLocation) {
		this.rootLocation = rootLocation;
	}

	@Override
//	存储传入的文件
	public void store(MultipartFile file) {
		try {
			if (file.isEmpty()) {
				log.error("Failed to store empty file.");
				return;
			}
//			由StorageProperties中设置的根路径配和传入文件名获得目标路径
			Path destinationFile = this.rootLocation.resolve(
					Paths.get(file.getOriginalFilename()))
					.normalize().toAbsolutePath();
			if (!destinationFile.getParent().equals(this.rootLocation.toAbsolutePath())) {
				// This is a security check
				log.error(
						"Cannot store file outside current directory.");
				return;
			}
//			覆盖式存入指定路径
			try (InputStream inputStream = file.getInputStream()) {
				Files.copy(inputStream, destinationFile,
					StandardCopyOption.REPLACE_EXISTING);
			}
		}
		catch (IOException e) {
			log.error("Failed to store file.", e);
		}
	}

	@Override
//	读取根路径下的所有文件的相对路径
	public Stream<Path> loadAll() {
		try {
			return Files.walk(this.rootLocation, 1)
				.filter(path -> !path.equals(this.rootLocation))
//					解析出根路径下所有文件的相对路径
				.map(this.rootLocation::relativize);
		}
		catch (IOException e) {
			log.error("Failed to read stored files", e);
		}

		return null;
	}

	@Override
//	获得指定文件的绝对路径
	public Path load(String filename) {
//		根据根路径和传入的文件名组成绝对路径
		return rootLocation.resolve(filename);
	}

	@Override
	//从指定根路径下读取传入文件名的文件
	public Resource loadAsResource(String filename) {
		try {
			Path file = load(filename);
			Resource resource = new UrlResource(file.toUri());
			if (resource.exists() || resource.isReadable()) {
				return resource;
			}
			else {
				throw new StorageFileNotFoundException(
						"Could not read file: " + filename);

			}
		}
		catch (MalformedURLException e) {
			throw new StorageFileNotFoundException("Could not read file: " + filename, e);
		}
	}

	@Override
	//	递归删除
	public void deleteAll() {
		FileSystemUtils.deleteRecursively(rootLocation.toFile());
	}

	@Override
	//	初始化根路径
	public void init() {
		try {
			if (Files.isDirectory(rootLocation))
				Files.createDirectories(rootLocation);
			else log.info("该文件夹已存在");
		}
		catch (IOException e) {
			throw new StorageException("Could not initialize storage", e);
		}
	}
}
